﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WXApi.Model;
using WxTenpay.Service.Model;
using WxTenpay.Service;
using System.Transactions;
using Newtonsoft.Json.Linq;

namespace WXApi.Controllers.SysApi
{


    /// <summary>
    /// 菜单、权限管理、管理
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiController]
    [Action]
    public class SysMenuController : ReqDataControllerBase
    {
        private readonly ISysMenu sysmenu;
        private readonly ISysMenuButton sysmenubutton;
        private readonly ISysLog syslog;
        private readonly ISysLoginLog sysloginlog;
        public SysMenuController(ISysLog _syslog, ISysMenu _sysmenu, ISysMenuButton _sysmenubutton, ISysLoginLog _sysloginlog)
        {
            syslog = _syslog;
            sysmenu = _sysmenu;
            sysmenubutton = _sysmenubutton;
            sysloginlog = _sysloginlog;
        }

        #region 获取菜单数据
        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSysMenu()
        {
            try
            {
                var token = HttpContext.Items["token"].ToString();
                var usergid = GetUser(token);
                var list = sysmenu.GetList();

                var btnlis = sysmenubutton.GetList();
                var data = getmenu(list, btnlis);
                var rdata = new
                {
                    data,
                    list
                };

                return Success(rdata);
            }
            catch (Exception ex)
            {

                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysMenu/GetSysMenu", Content = ex.ToString(), Name = "获取菜单数据" };
                return ErrorLog(model);
            }
        }
        #endregion


        #region 保存菜单数据
        /// <summary>
        /// 保存菜单数据
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult Addmenu([FromBody] MenuDto menudto)
        {
            try
            {
                var menu = menudto.menu;
                var lis = menudto.lis;
                if (string.IsNullOrWhiteSpace(menu.GuId)) //新增
                {
                    menu.Create();
                    using (TransactionScope tran = new TransactionScope())
                    {
                        sysmenu.Add(menu);

                        lis = lis.Select(x =>
                        {

                            x.Create();
                            x.MenuGuId = menu.GuId;
                            return x;

                        }).ToList();

                        sysmenubutton.AddList(lis);
                        tran.Complete();
                    }


                    SuccessLogDto loginmodel = new SuccessLogDto();
                    loginmodel.data = "操作成功";
                    loginmodel._sysloginlog = sysloginlog;
                    loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 1, Content = "新增菜单信息" };
                    return SuccessLog(loginmodel);


                }
                else
                {   //修改数据
                    var model = sysmenu.GetModel(x => x.GuId == menu.GuId);
                    if (model != null)
                    {
                        model.Address = menu.Address;
                        model.Icon = menu.Icon;
                        model.Name = menu.Name;
                        model.ParentId = menu.ParentId;
                        model.Sort = menu.Sort;
                        model.Type = menu.Type;


                        using (TransactionScope tran = new TransactionScope())
                        {
                            sysmenu.Update(model);


                            var buttonlis = sysmenubutton.GetList(x => x.MenuGuId == model.GuId, x => x.Id);
                            lis.ForEach(x =>
                            {
                                if (string.IsNullOrWhiteSpace(x.GuId))
                                {
                                    x.Create();
                                    x.MenuGuId = model.GuId;
                                    sysmenubutton.Add(x);
                                }
                                else
                                {
                                    var buttonmodel = buttonlis.FirstOrDefault(p => p.GuId == x.GuId);
                                    if (buttonmodel != null) //修改数据
                                    {
                                        buttonlis.Remove(buttonmodel);
                                        buttonmodel.Name = x.Name;
                                        buttonmodel.Number = x.Number;
                                        sysmenubutton.Update(buttonmodel);
                                    }
                                }

                            });
                            if (buttonlis.Count > 0)
                            {
                                //移除没有数据的菜单
                                sysmenubutton.Delete(string.Join(",", buttonlis.Select(p => p.Id)));
                            }
                            tran.Complete();
                        }

                        SuccessLogDto loginmodel = new SuccessLogDto();
                        loginmodel.data = "操作成功";
                        loginmodel._sysloginlog = sysloginlog;
                        loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 1, Content = "修改菜单信息" };
                        return SuccessLog(loginmodel);

                    }
                    else
                        return Error("参数错误！");

                }

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysMenu/Addmenu", Content = ex.ToString(), Name = "保存菜单数据" };
                return ErrorLog(model);
            }

        }
        #endregion


        /// <summary>
        /// 删除菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelSysMenu(JObject jobject)
        {
            try
            {
                string guid = jobject["guid"].ToString();
                if (string.IsNullOrWhiteSpace(guid))
                    return Error("参数错误！");

                using (TransactionScope tran = new TransactionScope())
                {
                    sysmenu.Delete(x => x.GuId == guid);//移除菜单
                    sysmenubutton.Delete(x => x.MenuGuId == guid); //移除菜单按钮事件

                    tran.Complete();
                }

                SuccessLogDto loginmodel = new SuccessLogDto();
                loginmodel.data = "操作成功";
                loginmodel._sysloginlog = sysloginlog;
                loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 3, Content = "删除菜单信息" };
                return SuccessLog(loginmodel);

            }
            catch (Exception ex)
            {

                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysMenu/DelSysMenu", Content = ex.ToString(), Name = "删除菜单数据" };
                return ErrorLog(model);
            }
        }



        /// <summary>
        /// 获取菜单列表数据
        /// </summary>
        /// <param name="lis"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private object getmenu(List<SysMenuEntity> lis, List<SysMenuButtonEntity> btnlis, string ParentId = "0")
        {
            try
            {
                var list = lis.Where(x => x.ParentId == ParentId).Select(x =>
                {
                    return new
                    {
                        Id = x.Id,
                        GuId = x.GuId,
                        Icon = x.Icon,
                        Name = x.Name,
                        Type = x.Type,
                        Address = x.Address,
                        Sort = x.Sort,
                        ParentId = x.ParentId,
                        Btnlis = btnlis.Where(p => p.MenuGuId == x.GuId),
                        children = getmenu(lis, btnlis, x.Id.ToString())
                    };


                });

                return list;

            }
            catch (Exception)
            {

                throw;
            }

        }



    }
}
